#!/bin/python3

import sys, os
import subprocess
import time

import pyotp
import pyperclip

from storage import Storage
from args import args, unknown_args
from config import config
from notify import notify_send

def main():
    if args.create:
        storage = Storage(storage_name=str(args.create))
        storage.create()
        sys.exit()

    if args.export_storage:
        subprocess.run(["/usr/bin/tar",
            "-cvf",
            f"{ unknown_args[0] if unknown_args[0] else 'arcalvus' }_{time.strftime('%Y-%m-%d')}.tar",
            "-C",
            str(config.storage_dir), "./"])
        sys.exit()

    if args.import_storage:
        if not os.path.isfile( args.import_storage ):
            print(f"File `{args.import_storage}` not found.", file=sys.stderr)
            sys.exit(1)

        subprocess.run(["/usr/bin/tar", "-xvf", str(args.import_storage), "-C", str(config.storage_dir)])
        sys.exit()

    if args.edit_config:
        subprocess.run(["/usr/bin/nano", config.config_path])
        sys.exit()

    if args.set_gpg_key:
        config.set_gpg_key(args.set_gpg_key)
        sys.exit()

    if not args.create:
        storage = Storage( str(unknown_args[0]) if unknown_args[0] else None )

        if args.get_password:
            get = "password"

        elif args.get_login:
            get = "login"

        elif args.get_mail:
            get = "mail"

        elif args.get_otp:
            get = "otp"

        elif args.get:
            get = str(args.get).lower()

        elif args.edit | args.open:
            storage.edit()

    out = storage[ str(get) ]

    if not out:
        print("None")
        sys.exit()

    match str(get):
        case "otp":
            otp_key = storage["otp"]
            if not otp_key:
                print("None")
                sys.exit()

            totp = pyotp.TOTP(otp_key)
            totp_temp_key = totp.now()

            pyperclip.copy(totp_temp_key)
            notify_send(f"`{get}` Copied To Clipboard.")

            print( totp_temp_key )

            sys.exit()

    pyperclip.copy(str(out))
    notify_send(f"`{get}` Copied To Clipboard.")

    if str(get) in ["password", "cvv", "cvc", "otp"] and not args.show:
        print( "*" * len(out) )
    else:
        print(out)


if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        print(f"Arcalvus: `Unknown error`\n`{error}`.", file=sys.stderr)
        sys.exit(1)
